package com.wtb.pub;

import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Constructor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wtb.thread.RrWriteThread;

/**
 * 
 * 子线程抛出异常 重新创建
 * @author tacheno
 *
 */
public class UnCachException implements UncaughtExceptionHandler {
	private static final Log log = LogFactory.getLog(RrWriteThread.class);
	private Runnable runnable;
	public UnCachException(Runnable runnable){
		this.runnable = runnable;
	}	
	public void uncaughtException(Thread t, Throwable e) {
		String threadName = t.getName();
		log.error(threadName+"线程异常", e);
		try {
			Constructor<? extends Thread> constructor = t.getClass().getConstructor(Runnable.class,String.class);
			t = constructor.newInstance(runnable,threadName);
			UnCachException exceptionHandler = new UnCachException(runnable);
			t.setUncaughtExceptionHandler(exceptionHandler);
			t.start();
			log.info(threadName + "重新创建实例并执行！");
		
		} catch (Exception e1) {
			log.error("重新创建"+threadName+"实例失败", e1);
			throw new WtbException("重新创建"+threadName+"实例失败", e1);
		} 
	}

}
